package com.servlet;

import com.dao.imp.AddUpdDelDaoImp;
import com.dao.imp.FindGoodsDaoImp;
import org.apache.commons.collections.functors.IfClosure;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author Mathison
 * @Title: ${NAME}
 * @Package: ${PACKAGE_NAME}
 * @Description: TODO
 * @date 2021/11/25 19:18
 **/

@WebServlet(name = "AddToCartServlet", value = "/AddToCartServlet")
public class AddToCartServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int good_amount = Integer.parseInt(request.getParameter("count"));
        int good_id = Integer.parseInt(request.getParameter("good_id"));
        HttpSession session = request.getSession();
        Object userId = session.getAttribute("userId");
        int user_id = Integer.parseInt(userId.toString());

        String sql = "";
        String selectSql = "SELECT * FROM shopingchart WHERE user_id="+user_id+" AND good_id="+good_id;
        FindGoodsDaoImp findGoodsDaoImp = new FindGoodsDaoImp();
        List<Map> goods = findGoodsDaoImp.findGoods(selectSql);
//        System.out.println(goods.toString()+goods.isEmpty());
        if (!goods.isEmpty()){
            int count = Integer.parseInt(goods.get(0).get("good_amount").toString());
            count += good_amount;
            sql = "UPDATE shopingchart SET good_amount="+count+" WHERE user_id="+user_id+" AND good_id="+good_id;
        }else {
            sql = "INSERT INTO shopingchart (good_id, user_id, good_amount) VALUES (" +
                    good_id+"," +
                    user_id+" ," +
                    good_amount +
                    ")";
        }



        AddUpdDelDaoImp addUpdDelDaoImp = new AddUpdDelDaoImp();
        boolean addResult = addUpdDelDaoImp.addUpdDelGoods(sql);
//        System.out.println(addResult);
    }
}
